package com.greenline.search.test.httprequest.impl;

import com.greenline.search.test.httprequest.MyHttpRequest;
import com.greenline.search.test.httprequest.ResponseInfo;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.*;

/**
 * Created with IntelliJ IDEA.
 * User: liulei
 * Date: 13-9-24
 * Time: 下午2:13
 * To change this template use File | Settings | File Templates.
 */
public class MyHttpClientRequest implements MyHttpRequest,Serializable {
    private Logger logger = LoggerFactory.getLogger(MyHttpClientRequest.class);

    @Override
    public byte[] request(String url) {
        // Create an instance of HttpClient.
        HttpClient client = new HttpClient();

        // Create a method instance.
        GetMethod method = new GetMethod(url);

        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed: " + method.getStatusLine());
            }

            // Read the response body.
            return method.getResponseBody();

        } catch (HttpException e) {
            logger.error("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
        return new byte[0];
    }

    @Override
    public ResponseInfo requestAndGetResponseInfo(String url) {
        ResponseInfo responseInfo = new ResponseInfo();
        // Create an instance of HttpClient.
        HttpClient client = new HttpClient();

        // Create a method instance.
        GetMethod method = new GetMethod(url);

        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        try {
            // Execute the method.
            int statusCode = client.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed: " + method.getStatusLine());
            }

            // Read the response body.
            byte[] responseBody = method.getResponseBody();

            // Deal with the response.
            // Use caution: ensure correct character encoding and is not binary data
            String responseString =  new String(responseBody);
            if(responseString.length() > 0){
                int indexOfCount = responseString.indexOf("count");
                int indexOfFirstComma = responseString.indexOf(",");
                int indexOfQtime = responseString.indexOf("qtime");
                int indexOfSecondComma = responseString.indexOf(",",indexOfQtime);
                String strCount = responseString.substring(indexOfCount+7,indexOfFirstComma);
                String strQtime = responseString.substring(indexOfQtime+7,indexOfSecondComma);
                responseInfo.setQueryTimeMills(Integer.parseInt(strQtime));
                responseInfo.setReturnCount(Integer.parseInt(strCount));
                if(strCount.equals("0")){
                //    logger.info("The request url is: " + url);
                }
            }
        } catch ( StringIndexOutOfBoundsException e) {
            logger.error("Fatal error: " + e.getMessage());
            responseInfo.setQueryTimeMills(-1);
            responseInfo.setReturnCount(-1);
        } catch (HttpException e) {
            logger.error("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // Release the connection.
            method.releaseConnection();
        }
        return responseInfo;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String url = "http://10.10.100.151:10000/doctor_search?q=";
        MyHttpRequest myHttpRequest = new MyHttpClientRequest();
        ResponseInfo info = myHttpRequest.requestAndGetResponseInfo(url+URLEncoder.encode("脑膜炎球菌性脑膜炎","UTF-8"));
        System.out.println(info.getQueryTimeMills());
        System.out.println(info.getReturnCount());
    }
}
